<?php

namespace app\common\model;

use think\Model;
use app\common\traits\model\TraitModel;

/**
 * 配置模型
 */
class Settings extends Model
{
    use TraitModel;
    protected static $user_model = 'Users';

    protected $type = [
        'profiles'    =>  'json'
    ];

    protected $config = ['finance' => ['rate', 'alipay', 'bank_card']];

    public function getConfigs($type = 'finance')
    {
        return $this->config[$type];
    }
    /**
     * 创建配置项
     * @param  [type] $settings_info [description]
     * @return [type]                [description]
     */
    public function createSettings($settings_info)
    {
    	return self::create($settings_info, true);
    }
    /**
     * 修改配置项
     * @param  [type] $settings_info [description]
     * @param  [type] $where         [description]
     * @return [type]                [description]
     */
    public function updateSettings($settings_info ,$where = null)
    {
    	return self::update($settings_info, $where, true);
    }
    /**
     * 删除配置项
     * @param  array  $where [description]
     * @return [type]        [description]
     */
    public function deleteSettings($where = [])
    {
    	if (empty($where)) {
    		return ;
    	}
    	return self::destory($where);
    }
    /**
     * 获取配置信息
     * @param  [type] $short_name [description]
     * @param  string $field      [description]
     * @return [type]             [description]
     */
    public function getSettings($short_name, $field = '', $array = false)
    {
    	if (!$short_name) {
    		return ;
    	}
    	if (strpos($short_name, '.')) {
    		list($k1, $k2) = explode('.', $short_name, 2);
    		$settings = json_decode(self::where(['short_name' => $k1])->value('profiles'));
    		$settings = isset($settings->$k2) ? $settings->$k2 : '';
    	}else {
    		$settings = json_decode(self::where(['short_name' => $short_name])->value('profiles'));
    	}
        if (is_bool($field)) {
            $array = $field;
            $field = '';
        }
    	if ($settings && $field) {
    		if ($field) {
    			if (strpos($field, '.')) {
    				list($k1, $k2) = explode('.', $field, 2);
    				$settings = isset($settings->$k1->$k2) ? $settings->$k1->$k2 : '';
    			}else {
    				$settings = isset($settings->$field) ? $settings->$field : '';
    			}
	    	}
    	}
        if ($array && $settings instanceof \stdClass) {
            return json_decode(json_encode($settings), true);
        }
    	return $settings;
    }
}
